package com.itheima.server.service;

import com.itheima.dubbo.api.UserApi;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.domain.User;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private SmsTemplate smsTemplate;

    @DubboReference
    private UserApi userApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @Autowired
    private MqMessageService mqMessageService;

    public static final String CHECK_CODE = "CHECK_CODE_";

    public void sendMsg(String phone) {
//        1. 生成一个验证码
        String code = "123456";//RandomStringUtils.randomNumeric(6);
//        2. 把验证码存储到redis中
        redisTemplate.opsForValue().set(CHECK_CODE+phone,code, Duration.ofMinutes(5)); //5分钟失效
//        3. 调用阿里云发送短信
       // smsTemplate.sendSms(phone,code);

    }

    /**
     * 登录验证
     * @param phone 手机号
     * @param verificationCode 验证码
     * @return
     */
    public Map<String,Object> verificationCode(String phone, String verificationCode) {
        //1. 校验验证码,删除验证码
        String redisCode = redisTemplate.opsForValue().get(CHECK_CODE + phone);
        if(redisCode==null||!redisCode.equals(verificationCode)){
            //验证码错误
            throw new RuntimeException("验证码错误");
        }
        //验证码校验成功，删除验证码
        redisTemplate.delete(CHECK_CODE + phone);

        //2. 根据手机号去查找用户，判断是否为新用户,如果是新用户需要插入新数据
        User user = userApi.findByMobile(phone);
        boolean isNew = false;
        //定义type记录用户行为类型
        String type = "0101"; //默认是登录行为
        if(user==null){
            //如果是新用户需要插入新数据
            user = new User();
            user.setMobile(phone);
            user.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
            Long userId = userApi.save(user);
            user.setId(userId);
            isNew  =true;
            // 把当前用户注册到环信通讯云 用户名： hx123  密码：统一都是123456
            huanXinTemplate.register(Constants.HX_USER_PREFIX+user.getId(),Constants.INIT_PASSWORD);
            //保存环信账号与密码到数据库中
            user.setHxUser(Constants.HX_USER_PREFIX+user.getId());
            user.setHxPassword(Constants.INIT_PASSWORD);
            userApi.update(user);
            type="0102"; //注册行为
        }

        //发送消息到rabbitmq
//        Map<String,Object> paramMap = new HashMap<>();
//        paramMap.put("userId",user.getId());
//        paramMap.put("type",type);
//        paramMap.put("date",new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
//        rabbitTemplate.convertAndSend("tanhua.log.exchange","log.user",paramMap);
         mqMessageService.sendLogService(user.getId(),type,"user","");

        //3. 生成oken
        Map<String,Object> claims = new HashMap<>();
        claims.put("id",user.getId());
        claims.put("mobile",user.getMobile());
        String token = JwtUtils.getToken(claims);

        //4. 返回结果
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("token",token);
        resultMap.put("isNew",isNew);
        return resultMap;
    }
}
